<template lang="pug">
data-page
  el-row.registration(
    :gutter="8"
  )
    el-col.h100(:span="10" style="display: flex;flex-direction: column;overflow: hidden;")
      mt-card.registrationCard
        .registrationCard__content
          .registrationCard__content-title
            SectionTitle(
              :padding="[0, 'var(--mt-padding)']"
            ) 检查信息
          .registrationCard__content-body
            el-scrollbar
              registrationForm(
                :selectRegistration="selectRegistration"
                :isRegistration= "isRegistration" 
                style="margin-top: var(--mt-margin)"
                ref="registrationFormRef" 
              )
      .projectCard
        el-row(:gutter="10")
          el-col(:span="12")
            mt-card
              .div(
                style="height: 100%;display:flex;flex-direction: column;overflow: hidden;"
              )
                SectionTitle(
                  :padding="[0, 'var(--mt-padding)']"
                ) 检查设备
                equipment(:selectRegistration="selectRegistration",@changEquipment = "changEquipment")
              //- registrationProject(:selectRegistration="selectRegistration" @changEquipment = "changEquipment"  @changProject="changProject")
          el-col(:span="12")
            mt-card
              .div(
                style="height: 100%;display:flex;flex-direction: column;overflow: hidden;"
              )
                SectionTitle(
                  :padding="[0, 'var(--mt-padding)']"
                ) 检查项目
                registrationProject(:selectRegistration="selectRegistration" @changEquipment = "changEquipment"  @changProject="changProject",@changPart="changPart")
              //- registrationPart(:selectRegistration="selectRegistration" @changPart="changPart")
      .bottomCard
        .bottomCard__left
          mt-button(type="primary",@click="clearBtnClick") 清空
          mt-button(type="primary",@click="addBtnClick",:disabled="!isRegistration") 新增登记
          mt-button(type="primary",@click="registBtnClick" ,:disabled="isRegistration",:loading="loadingMap['addRegister']") 确认登记
        .bottomCard__right
          //- el-checkbox(style="margin-left: 20px;",:disabled="isRegistration") 登记拆分部位
          el-checkbox(:disabled="isRegistration",v-model="isPrint") 打印登记单
          el-checkbox(:disabled="isRegistration",v-model="isPrintBarCode") 打印条码
    el-col(:span="14")
      mt-card.registrationListCard
        mt-tabs(
          v-model="activeName"
        )
          mt-tab-pane(
            name="his申请"
            label="his申请"
          )
            hisregistration(ref="hisregistrationRef",v-model="hisregistrationItem")
          mt-tab-pane(name="登记信息",label="登记信息")
            registrationList(ref="registrationListRef",v-model="registration")
  templatePreview(v-model="printShow",:selectRow="selectRegistrationItem ?? {}")
  SpecimenPacsPrint(v-model="barCodeShow",:specimen="registrationId")
</template>
<script setup lang="ts">
import { SpecimenPacsPrint } from "@scmt/common-api-components";
import hisregistration from "./components/hisRegistrationt.vue";
import registrationForm from "./components/registrationForm.vue";
import registrationList from "./components/registrationList.vue";
// import registrationPart from "./components/registrationPart.vue";
import registrationProject from "./components/registrationProject.vue";
import equipment from "./components/equipment.vue";

import { SectionTitle, useNotify } from "@scmt/common-components";
import { useRequest } from "@scmt/common-hooks";
import { useApi } from "@scmt/core-api";
import type { RegistrationEntity } from "@scmt/api-pacs-registration";
import type { RegistrationProjectEntity } from "@scmt/api-pacs-registration-project";
import type { PartEntity } from "@scmt/api-pacs-part";
import { useUser } from "@scmt/common-store";
import { ExecutionStatus, PatientType } from "@scmt/api-common";
import templatePreview from "./components/templatePreview.vue";

const user = useUser();
const isRegistration = ref(true);
const $api = useApi();
const $notify = useNotify();
const activeName = ref<null | String>("his申请");
const selectRegistration = ref<RegistrationEntity>(
  $api.pacs.registration.$$createEntity({})
);

const selectRegistrationItem = ref<RegistrationEntity>(
  $api.pacs.registration.$$createEntity({})
);
const hisregistrationItem = ref<Object>({});
const registration = ref<Object>({});
const registrationFormRef = ref<null | InstanceType<typeof registrationForm>>(
  null
);

const isPrintBarCode = ref(false);
const isPrint = ref(false);

const barCodeShow = ref(false);
const printShow = ref(false);
const registrationId = ref("");
// 获取子组件的引用
const hisregistrationRef = ref<InstanceType<typeof hisregistration>>();
const registrationListRef = ref<InstanceType<typeof registrationList>>();
const { request, data, loadingMap } = useRequest({
  //查询登记单下面关联的项目
  registrationProject: async (params: any) => {
    return await $api.pacs.project.queryPacsProjectListByRegistrationId(params);
  },
  //查询登记单下面关联部位
  registrationPart: async (params: any) => {
    return await $api.pacs.part.queryPacsPartListByRegistrationId(params);
  },
  //确认定价
  addRegister: (model: RegistrationEntity) => {
    return $api.pacs.registration.addRegister(model).then(() => {
      loadingMap.addRegister = false;
      isRegistration.value = true;
      $notify.success("保存成功");
      selectRegistration.value = $api.pacs.registration.$$createEntity({});
      if (hisregistrationRef && hisregistrationRef.value) {
        hisregistrationRef.value.handleQuery({});
      }
      if (registrationListRef && registrationListRef.value) {
        registrationListRef.value.handleQuery({});
      }
      selectRegistrationItem.value = model;
      nextTick(() => {
        if (registrationFormRef && registrationFormRef.value) {
          registrationFormRef.value.clearValidation();
        }
        //初始化打印相关数据变量
        isPrint.value = false;
        isPrintBarCode.value = false;
      });
      if (isPrint.value) {
        printShow.value = true;
      }
      if (isPrintBarCode.value) {
        registrationId.value = model.id;
        barCodeShow.value = true;
      }

    });
  },
  //更新住院医嘱执行单状态
  updateExecutionStatus: (params: any) => {
    return $api.medical.medicalOrderExecution.updateExecutionStatus(params);
  },
});
//初始化打印相关数据变量
const initPrintData = () => {
  printShow.value = false;
  isPrint.value = false;
  isPrintBarCode.value = false;
  barCodeShow.value = false;
}
//清空按钮点击事件
const clearBtnClick = () => {
  //初始化打印相关数据变量
  initPrintData();
  selectRegistration.value = $api.pacs.registration.$$createEntity({ id: "id" });
  nextTick(() => {
    selectRegistration.value = $api.pacs.registration.$$createEntity({});
    if (registrationFormRef && registrationFormRef.value) {
      registrationFormRef.value.clearValidation();
    }
  });

};
//新增登记按钮点击事件
const addBtnClick = () => {
  isRegistration.value = false;
  selectRegistration.value = $api.pacs.registration.$$createEntity({});
  if (registrationFormRef && registrationFormRef.value) {
    registrationFormRef.value.clearValidation();
  }
};
//登记按钮点击事件
const registBtnClick = () => {
  registrationFormRef.value?.validate((valid, model) => {
    if (valid) {
      const item = $api.pacs.registration.$$createEntity(
        selectRegistration.value
      );
      model.registrationProjectList = item.registrationProjectList;
      model.registrationPartList = item.registrationPartList;
      model.deviceId = item.deviceId;
      if (!model.deviceId || model.deviceId.trim().length == 0) {
        $notify.warning("请选择一台设备!!!");
        return;
      }
      if (model.registrationProjectList.length == 0) {
        $notify.warning("请选择一项检查项目!!!");
        return;
      }
      loadingMap.addRegister = true;
      request("addRegister", model);
      //是住院才更新住院医嘱执行单状态
      if (model.patientType == PatientType.INPATIENT) {
        request("updateExecutionStatus", {
          executionNumberList: [model.sourceId],
          executionId: user.userId,
          executionName: user.username,
          executionStatus: ExecutionStatus.IN_PROGRESS,
        });
      }
    }
  });
};
/**
 * 设备改变事件
 * @param deviceId  设备ID
 */
const changEquipment = (deviceId: any) => {
  selectRegistration.value.deviceId = "";
  if (deviceId && deviceId.trim().length > 0) {
    selectRegistration.value.deviceId = deviceId;
  }
};

/**
 * 项目改变
 * @param projectTableData  项目数据
 */
const changProject = (projectTableData: Array<RegistrationProjectEntity>) => {
  if (projectTableData && projectTableData.length > 0) {
    selectRegistration.value.registrationProjectList = [];
    projectTableData.forEach((ii) => {
      let model = {
        deviceId: selectRegistration.value.deviceId,
        registrationId: selectRegistration.value.id,
        projectName: ii.projectName,
        projectCode: ii.projectCode,
        projectPrice: ii.projectPrice,
        projectId: ii.id,
        partId: ii.partId,
        partName: ii.partName,
      };
      selectRegistration.value.registrationProjectList.push(model);
    });
  }
};
/**
 * 部位改变事件
 * @param deviceId  设备ID
 */
const changPart = (partData: Array<PartEntity>) => {
  if (partData && partData.length > 0) {
    selectRegistration.value.registrationPartList = [];
    partData.forEach((i) => {
      let model = {
        deviceId: selectRegistration.value.deviceId,
        registrationId: selectRegistration.value.id,
        partName: i.partName,
        partCode: i.partCode,
        partId: i.id,
      };
      selectRegistration.value.registrationPartList.push(model);
    });
  }
};
watch(
  () => hisregistrationItem.value,
  async (item) => {
    //初始化打印相关数据变量
    initPrintData();
    if (item) {
      const selectRegistrationHis = ref<RegistrationEntity>(
        $api.pacs.registration.$$createEntity({})
      );
      selectRegistrationHis.value = $api.pacs.registration.$$createEntity(item);
      if (selectRegistrationHis.value.id) {
        isRegistration.value = false;
        await request("registrationProject", {
          deviceId: selectRegistrationHis.value.deviceId,
          registrationId: selectRegistrationHis.value.id,
        });
        let registrationProject =
          data.registrationProject instanceof Array
            ? data.registrationProject
            : [];
        selectRegistrationHis.value.registrationProjectList =
          registrationProject;
        await request("registrationPart", {
          deviceId: selectRegistrationHis.value.deviceId,
          registrationId: selectRegistrationHis.value.id,
        });
        selectRegistrationHis.value.registrationPartList =
          data.registrationPart instanceof Array ? data.registrationPart : [];
      }
      selectRegistration.value = selectRegistrationHis.value;

    }
  },
  {
    immediate: true,
  }
);
watch(
  () => registration.value,
  (item) => {
    if (item) {
    }
  },
  {
    immediate: true,
  }
);
//监听科室改变
watch(
  () => user.currentOfficeId,
  (item) => {
    if (item) {
      clearBtnClick();
      isRegistration.value = true;
    }
  },
  {
    immediate: true,
  }
);
</script>

<style lang="less" scoped>
.registration {
  height: 100%;
  overflow: hidden;

  :deep(.mt-card) {
    box-shadow: none;

    &__content {
      padding: var(--mt-padding);
    }
  }

  :deep(.section-title) {
    padding: 0 var(--mt-padding);

    h4 {
      font-size: 17px;

    }
  }

  .el-col {
    height: 100%;

    .registrationListCard {
      height: 100%;
      box-sizing: border-box;
      min-width: 600px;

      .mt-tab-pane {
        padding-top: 10px;
        height: calc(100% - 10px);
      }
    }

    .registrationCard {
      height: 36%;
      margin-bottom: var(--mt-margin);
      overflow: hidden;

      :deep(.mt-card__content) {
        padding: 0px;
      }

      &__content {
        height: 100%;
        display: flex;
        flex-direction: column;
        overflow: hidden;

        &-title {
          flex-shrink: 0;
          padding-left: var(--mt-padding);
          padding-top: var(--mt-padding);
        }

        &-body {
          flex: 1;
          overflow: hidden;

          .el-scrollbar {
            padding: var(--mt-padding);
          }
        }
      }
    }

    .projectCard {
      height: 58%;
      margin-bottom: var(--mt-margin);

      :deep(.el-row) {
        height: 100%;
      }

      :deep(.mt-card__content) {
        display: flex;
        flex-direction: column;
      }
    }

    .bottomCard {
      flex-shrink: 0;
      background-color: var(--el-color-white);
      border: 1px solid var(--el-border-color-light);
      border-radius: 4px;
      box-sizing: border-box;
      padding: var(--mt-padding);
      display: flex;
      justify-content: flex-end;

      &__right {
        margin-left: var(--mt-margin);
      }
    }
  }
}
</style>
